package com.gzxw.mogublog.admin.security;

import cn.hutool.core.lang.UUID;
import com.gzxw.mogublog.commons.config.jwt.Audience;
import com.gzxw.mogublog.commons.config.jwt.JwtTokenUtil;
import com.gzxw.mogublog.commons.entity.Admin;
import com.gzxw.mogublog.xo.global.SysConf;
import com.gzxw.mogublog.xo.service.AdminService;
import com.gzxw.mogublog.commons.config.security.LoginUser;
import com.gzxw.mogublog.xo.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class AuthenticationService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Value(value = "${isRememberMeExpiresSecond}")
    private int isRememberMeExpiresSecond; // 是否记住我

    @Autowired
    private Audience audience;

    @Autowired
    private TokenService tokenService;

    // 登录服务
    public String login(String username, String password, Boolean isRememberMe) {

        // 判断登录次数
        // 判断username是否为邮箱
        // 判断username是否为手机号
        Authentication authenticate = null;

        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            SecurityContextHolder.getContext().setAuthentication(authenticate);
            authenticate = authenticationManager.authenticate(authenticationToken);
        } catch (AuthenticationException e) {
//            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        } finally {
//            SecurityContextHolder.clearContext();
        }

        // 从完成的认证信息中取出principal，能取出说明登录成功了
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();

        // 生成token
        String token = UUID.randomUUID().toString(true);
        loginUser.setToken(token);

        // 将用户信息存入redis key-->token value-->用户信息
        tokenService.refreshToken(loginUser);

        return token;
    }
}
